//
//  FQDMainMenuViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 8/28/16.
//  Copyright © 2016 Xensius. All rights reserved.
//


#import "FQDMainMenuViewController.h"
#import "FQDNavigationController.h"
#import "FQDMainViewController.h"
#import "FQDHomeFeedViewController.h"
#import "FQDSettingsViewController.h"
#import "FQDSearchViewController.h"
#import "FQDSearchBarButton.h"
#import "FQDMenuItemCell.h"
#import "FQDMainQButton.h"
#import "FQDMenuItem.h"
#import "FQDMainMenuItemsCollection.h"
#import "UIButton+FQDExtension.h"
#import "UIView+FQDExtension.h"
#import "UIImage+ImageEffects.h"

#import "Masonry.h"

@interface FQDMainMenuViewController () <UICollectionViewDataSource,
                                         UICollectionViewDelegate,
                                         UICollectionViewDelegateFlowLayout,
                                         UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView *effectBgView;
@property (nonatomic, strong) UIVisualEffectView *effectView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;
// 底部可选主菜单列表
@property (nonatomic, strong) UICollectionView *mainMenuCollectionView;
// 底部可选子菜单列表
@property (nonatomic, strong) UICollectionView *subMenuCollectionView;
// 底部主菜单列表
@property (nonatomic, strong) NSArray *mainMenuItems;
// 底部子菜单列表
@property (nonatomic, strong) NSArray *subMenuItems;
// 菜单项集合
@property (nonatomic, strong) FQDMainMenuItemsCollection *menuItemsCollection;
// 点击关闭菜单手势
@property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;

@end

@implementation FQDMainMenuViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupBackground];
    [self setupBlurView];
    [self setupTopView];
    [self setupBottomView];
    [self setupBottomMenuItems];
    [self setupGestureRecognizers];
    
}

- (void)setupBackground
{
    self.view.backgroundColor = [UIColor clearColor];
}

- (void)setupBlurView
{
    self.effectBgView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.effectBgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view insertSubview:self.effectBgView atIndex:0];
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = self.view.bounds;
    effectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.effectBgView addSubview:effectView];
    self.effectView = effectView;
}

- (void)setupTopView
{
    CGFloat viewW = self.view.bounds.size.width;
    
    CGFloat topViewW = viewW;
    CGFloat topViewH = 167.0f;
    
    UIView *topView = [[UIView alloc] init];
    topView.frame = CGRectMake(0, 0, topViewW, topViewH);
    topView.backgroundColor = [UIColor clearColor];
    topView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:topView];
    self.topView = topView;
    
    FQDSearchBarButton *searchButton =[[FQDSearchBarButton alloc] init];
    [self.topView addSubview:searchButton];
    
    [searchButton addTarget:self action:@selector(startSearch:) forControlEvents:UIControlEventTouchUpInside];
    
    [searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView).offset(35);
        make.left.equalTo(topView).offset(28);
        make.right.equalTo(topView).offset(-28);
        make.height.equalTo(@36);
    }];
    
    UIButton *settingBtn = [UIButton topMenuButtonWithTitle:@"设置" iconName:@"sidebar_setting"];
    UIButton *switchNightBtn = [UIButton topMenuButtonWithTitle:@"夜间" iconName:@"sidebar_switchNight"];
    UIButton *offlineBtn = [UIButton topMenuButtonWithTitle:@"离线" iconName:@"sidebar_offline"];
    UIButton *shareBtn = [UIButton topMenuButtonWithTitle:@"推荐" iconName:@"sidebar_share"];
    
    [topView addSubview:settingBtn];
    [topView addSubview:switchNightBtn];
    [topView addSubview:offlineBtn];
    [topView addSubview:shareBtn];
    
    [settingBtn addTarget:self action:@selector(showSettings:) forControlEvents:UIControlEventTouchUpInside];
    [switchNightBtn addTarget:self action:@selector(switchNight:) forControlEvents:UIControlEventTouchUpInside];
    [offlineBtn addTarget:self action:@selector(offlineCache:) forControlEvents:UIControlEventTouchUpInside];
    [shareBtn addTarget:self action:@selector(shareNow:) forControlEvents:UIControlEventTouchUpInside];
    
    [settingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchButton.mas_bottom).offset(20);
        make.left.equalTo(topView.mas_centerX).offset(-132.5f);
        make.size.mas_equalTo(CGSizeMake(40, 60));
    }];
    
    [switchNightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(settingBtn);
        make.left.equalTo(topView.mas_centerX).offset(-57.5f);
        make.size.mas_equalTo(CGSizeMake(40, 60));
    }];
    
    [offlineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(settingBtn);
        make.left.equalTo(topView.mas_centerX).offset(17.5f);
        make.size.mas_equalTo(CGSizeMake(40, 60));
    }];
    
    [shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(settingBtn);
        make.left.equalTo(topView.mas_centerX).offset(92.5f);
        make.size.mas_equalTo(CGSizeMake(40, 60));
    }];
}

- (void)setupBottomView
{
    CGFloat viewW = self.view.bounds.size.width;
    
    CGFloat bottomViewW = viewW;
    CGFloat bottomViewH = 315.0f;
    CGFloat bottomViewX = 0;
    CGFloat bottomViewY = CGRectGetMaxY(self.topView.frame) + 12.0f;
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.frame = CGRectMake(bottomViewX, bottomViewY, bottomViewW, bottomViewH);
    bottomView.backgroundColor = [UIColor clearColor];
    bottomView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    [self setupBottomCollectionView];
}

- (void)setupBottomCollectionView
{
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bottomView.bounds];
    scrollView.contentSize = self.bottomView.frame.size;
    scrollView.alwaysBounceVertical = YES;
    scrollView.delaysContentTouches = NO;
    [self.bottomView addSubview:scrollView];
    
    [self setupMainMenuCollectionView];
    [self setupSubMenuCollectionView];
}

- (void)setupMainMenuCollectionView
{
    UICollectionViewFlowLayout *mainFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    mainFlowLayout.minimumLineSpacing = 0;
    mainFlowLayout.minimumInteritemSpacing = 10.0f;
    mainFlowLayout.sectionInset = UIEdgeInsetsMake(0, 28.0f, 0, 28.0f);
    mainFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *mainCollectionView =
    [[UICollectionView alloc] initWithFrame:self.bottomView.bounds
                       collectionViewLayout:mainFlowLayout];
    mainCollectionView.dataSource = self;
    mainCollectionView.delegate = self;
    mainCollectionView.backgroundColor = [UIColor clearColor];
    mainCollectionView.pagingEnabled = YES;
    mainCollectionView.showsHorizontalScrollIndicator = NO;
    mainCollectionView.scrollEnabled = NO;
    [self.bottomView addSubview:mainCollectionView];
    self.mainMenuCollectionView = mainCollectionView;
    
    [self.mainMenuCollectionView registerClass:[FQDMenuItemCell class]
                    forCellWithReuseIdentifier:[FQDMenuItemCell reuseId]];
    
    self.mainMenuCollectionView.hidden = NO;
    
}

- (void)setupSubMenuCollectionView
{
    UICollectionViewFlowLayout *subFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    subFlowLayout.minimumLineSpacing = 0;
    subFlowLayout.minimumInteritemSpacing = 10.0f;
    subFlowLayout.sectionInset = UIEdgeInsetsMake(0, 28.0f, 0, 28.0f);
    subFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *subCollectionView =
    [[UICollectionView alloc] initWithFrame:self.bottomView.bounds
                       collectionViewLayout:subFlowLayout];
    subCollectionView.dataSource = self;
    subCollectionView.delegate = self;
    subCollectionView.backgroundColor = [UIColor clearColor];
    subCollectionView.showsHorizontalScrollIndicator = NO;
    [self.bottomView addSubview:subCollectionView];
    self.subMenuCollectionView = subCollectionView;
    
    [self.subMenuCollectionView registerClass:[FQDMenuItemCell class]
                   forCellWithReuseIdentifier:[FQDMenuItemCell reuseId]];
    
    self.subMenuCollectionView.hidden = YES;
}

- (void)setupBottomMenuItems
{
    FQDActionMenuItem *item_about = [self.menuItemsCollection aboutMenuItem];
    FQDMenuItemContainer *item_category = [self.menuItemsCollection categoryMenuItem];
    FQDActionMenuItem *item_column = [self.menuItemsCollection columnMenuItem];
    FQDActionMenuItem *item_lab = [self.menuItemsCollection labMenuItem];
    FQDActionMenuItem *item_message = [self.menuItemsCollection messageMenuItem];
    FQDActionMenuItem *item_user = [self.menuItemsCollection userCenterMenuItem];
    FQDActionMenuItem *item_home = [self.menuItemsCollection homeMenuItem];
    
    self.mainMenuItems = @[item_about, item_category, item_column, item_lab, item_message, item_user, item_home];
    
}

- (void)setupGestureRecognizers
{
    self.tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
    self.tapRecognizer.delegate = self;
    [self.view addGestureRecognizer:self.tapRecognizer];
}

- (void)dismissSelfAndPushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
    [self.navigationController pushViewController:viewController animated:animated];
    [mainVC.qButton playBounceAnimation];
    [mainVC dismissMenuVC:YES];
}

- (void)dismissSelfAndPresentViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
    [self presentViewController:viewController animated:animated completion:nil];
    [mainVC.qButton playBounceAnimation];
    [mainVC dismissMenuVC:YES];
}

- (void)dismissSelfAnimated
{
    FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
    [mainVC.qButton playBounceAnimation];
    [mainVC dismissMenuVC:YES];
}

#pragma mark - Getters and Setters
- (FQDMainMenuItemsCollection *)menuItemsCollection
{
    if (!_menuItemsCollection) {
        _menuItemsCollection = [FQDMainMenuItemsCollection collectionWithMainMenuViewController:self];
    }
    return _menuItemsCollection;
}

#pragma mark - GestureRecognizers
- (void)backgroundTapped:(UIGestureRecognizer *)gr
{
    [self dismissSelfAnimated];
}

// 处理点击空白处关闭菜单界面
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    UIView *view = touch.view;
    
    if ([view isKindOfClass:[UIControl class]]) {
        return NO;
    }
    
    if ([view isDescendantOfView:self.mainMenuCollectionView] ||
        [view isDescendantOfView:self.subMenuCollectionView]) {
        
        UIView *targetView = view;
        while (targetView != self.mainMenuCollectionView &&
               targetView != self.subMenuCollectionView) {
            
            if ([targetView isKindOfClass:[FQDMenuItemCell class]]) {
                FQDMenuItemCell *cell = (FQDMenuItemCell *)targetView;
                CGPoint point = [touch locationInView:cell];
                if (CGRectContainsPoint([cell touchableRect], point)) {
                    return NO;
                } {
                    return YES;
                }
            }
            
            targetView = targetView.superview;
        }
    }
    
    return YES;
}

#pragma mark - Open & Close animation
- (void)animatingOpenWithCompletion:(void (^)(void))completion
{
    CGFloat viewH = CGRectGetHeight(self.view.bounds);
    CGFloat topViewMoveY = CGRectGetMaxY(self.topView.frame);
    CGFloat botViewMoveY = viewH - CGRectGetMinY(self.bottomView.frame);
    self.topView.layer.transform = CATransform3DMakeTranslation(0, -topViewMoveY, 0);
    self.bottomView.layer.transform = CATransform3DMakeTranslation(0, botViewMoveY, 0);
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.topView.layer.transform = CATransform3DIdentity;
        self.bottomView.layer.transform = CATransform3DIdentity;
    } completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)animatingCloseWithCompletion:(void (^)(void))completion
{
    CGFloat viewH = CGRectGetHeight(self.view.bounds);
    CGFloat topViewMoveY = CGRectGetMaxY(self.topView.frame);
    CGFloat botViewMoveY = viewH - CGRectGetMinY(self.bottomView.frame);
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:0.9 initialSpringVelocity:30.0f options:0 animations:^{
        self.topView.layer.transform = CATransform3DMakeTranslation(0, -topViewMoveY, 0);
        self.bottomView.layer.transform = CATransform3DMakeTranslation(0, botViewMoveY, 0);
        self.effectBgView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
    
}

#pragma mark - Expand & Contract Menu animation
- (void)expandMainMenu
{
    CGSize mainSize = self.mainMenuCollectionView.frame.size;
    CGSize subSize = self.subMenuCollectionView.frame.size;
    
    self.mainMenuCollectionView.hidden = NO;
    self.subMenuCollectionView.hidden = NO;
    self.mainMenuCollectionView.layer.transform = CATransform3DIdentity;
    self.subMenuCollectionView.layer.transform = CATransform3DMakeTranslation(subSize.width, 0, 0);
    [UIView animateWithDuration:0.45f delay:0 usingSpringWithDamping:0.80f initialSpringVelocity:12.0f options:UIViewAnimationOptionCurveEaseOut
     animations:^{
        self.mainMenuCollectionView.layer.transform = CATransform3DMakeTranslation(-mainSize.width, 0, 0);
        self.subMenuCollectionView.layer.transform = CATransform3DIdentity;
    } completion:^(BOOL finished) {
        self.mainMenuCollectionView.hidden = YES;
        self.subMenuCollectionView.hidden = NO;
    }];
}

- (void)contractMainMenu
{
    CGSize mainSize = self.mainMenuCollectionView.frame.size;
    CGSize subSize = self.subMenuCollectionView.frame.size;
    
    self.mainMenuCollectionView.hidden = NO;
    self.subMenuCollectionView.hidden = NO;
    self.mainMenuCollectionView.layer.transform = CATransform3DMakeTranslation(-mainSize.width, 0, 0);
    self.subMenuCollectionView.layer.transform = CATransform3DIdentity;
    [UIView animateWithDuration:0.45f delay:0 usingSpringWithDamping:0.80f initialSpringVelocity:12.0f options:0
     animations:^{
        self.mainMenuCollectionView.layer.transform = CATransform3DIdentity;
        self.subMenuCollectionView.layer.transform = CATransform3DMakeTranslation(subSize.width, 0, 0);
    } completion:^(BOOL finished) {
        self.mainMenuCollectionView.hidden = NO;
        self.subMenuCollectionView.hidden = YES;
    }];
    
}

#pragma mark - Event Response
- (void)startSearch:(id)sender
{
    FQDSearchViewController *searchVC = [[FQDSearchViewController alloc] init];
    FQDNavigationController *navVC = [[FQDNavigationController alloc] initWithRootViewController:searchVC];
    navVC.edgesForExtendedLayout = UIRectEdgeNone;
    navVC.navigationBarHidden = YES;
    [self presentViewController:navVC animated:YES completion:nil];
}

- (void)showSettings:(id)sender
{
    FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
    FQDSettingsViewController *settingsVC = [[FQDSettingsViewController alloc] init];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *screenshot = [[mainVC.homeFeedVC.view captureViewHierarchy] blurImageWithRadius:30.0f];
        dispatch_async(dispatch_get_main_queue(), ^{
            settingsVC.blurBgImage = screenshot;
        });
    });
    [self.navigationController pushViewController:settingsVC animated:YES];
}

- (void)switchNight:(id)sender
{
    
}

- (void)offlineCache:(id)sender
{
    
}

- (void)shareNow:(id)sender
{
    
}

#pragma mark - UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.mainMenuCollectionView) {
        return [self.mainMenuItems count];
    } else if (collectionView == self.subMenuCollectionView) {
        return [self.subMenuItems count];
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FQDMenuItemCell *cell = (FQDMenuItemCell *)
    [collectionView dequeueReusableCellWithReuseIdentifier:[FQDMenuItemCell reuseId]
                                              forIndexPath:indexPath];
    
    if (collectionView == self.mainMenuCollectionView) {
        cell.menuItem = self.mainMenuItems[indexPath.row];
    } else if (collectionView == self.subMenuCollectionView) {
        cell.menuItem = self.subMenuItems[indexPath.row];
    }
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.mainMenuCollectionView) {
        [self didSelectMainMenuItemAtIndexPath:indexPath];
    } else if (collectionView == self.subMenuCollectionView) {
        [self didSelectSubMenuItemAtIndexPath:indexPath];
    }
    
}

- (void)didSelectMainMenuItemAtIndexPath:(NSIndexPath *)indexPath
{
    FQDMenuItem *item = self.mainMenuItems[indexPath.row];
    if ([item isKindOfClass:[FQDMenuItemContainer class]]) {
        FQDMenuItemContainer *container = (FQDMenuItemContainer *)item;
        if ([container.subItems count] > 0) {
            self.subMenuItems = container.subItems;
            [self.subMenuCollectionView reloadData];
            
            [self.qButton playRushToAnimation];
            [self expandMainMenu];
        } else {
            // no category, do nothing...
        }
    } else {
        FQDActionMenuItem *actionItem = (FQDActionMenuItem *)item;
        if (actionItem.selectAction) {
            actionItem.selectAction();
        }
    }
}

- (void)didSelectSubMenuItemAtIndexPath:(NSIndexPath *)indexPath
{
    FQDActionMenuItem *actionItem = (FQDActionMenuItem *)self.subMenuItems[indexPath.row];
    if (actionItem.selectAction) {
        actionItem.selectAction();
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionViewLayout;
    UIEdgeInsets inset = flowLayout.sectionInset;
    CGFloat itemW = collectionView.frame.size.width - inset.left - inset.right;
    CGFloat itemH = 35.0f;
    if (collectionView == self.subMenuCollectionView) {
        itemW /= 2;
    }
    return CGSizeMake(itemW, itemH);
}

@end
